﻿using UnityEngine;
using System.Collections;

namespace CHFramework
{
    public class GameUlities
    {
        /// <summary>
        /// 查找子节点对象
        /// 内部使用“递归算法”
        /// </summary>
        /// <param name="goParent">父对象</param>
        /// <param name="chiildName">查找的子对象名称</param>
        /// <returns></returns>
        public static Transform FindTheChildNode(GameObject goParent, string chiildName)
        {
            Transform searchTrans = null;                   //查找结果

            searchTrans = goParent.transform.Find(chiildName);
            if (searchTrans == null)
            {
                foreach (Transform trans in goParent.transform)
                {
                    searchTrans = FindTheChildNode(trans.gameObject, chiildName);
                    if (searchTrans != null)
                    {
                        return searchTrans;

                    }
                }
            }
            return searchTrans;
        }

        /// <summary>
        /// 给子节点添加父对象
        /// </summary>
        /// <param name="parents">父对象的方位</param>
        /// <param name="child">子对象的方法</param>
        public static void AddChildNodeToParentNode(Transform parents, Transform child)
        {
            child.SetParent(parents, false);
            child.localPosition = Vector3.zero;
            child.localScale = Vector3.one;
            child.localEulerAngles = Vector3.zero;
        }

        /// <summary>
        /// 添加子物体
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="child"></param>
        public static void AddChildToParent(Transform parent, Transform child)
        {
            //check if this is ugui or (ngui)?
            Vector3 anchorPos = Vector3.zero;
            Vector2 sizeDel = Vector2.zero;
            Vector3 scale = Vector3.one;
            if (child.GetComponent<RectTransform>() != null)
            {
                anchorPos = child.GetComponent<RectTransform>().anchoredPosition;
                sizeDel = child.GetComponent<RectTransform>().sizeDelta;
                scale = child.GetComponent<RectTransform>().localScale;
            }
            else
            {
                anchorPos = child.transform.localPosition;
                scale = child.transform.localScale;
            }

            child.transform.SetParent(parent);

            if (child.GetComponent<RectTransform>() != null)
            {
                child.GetComponent<RectTransform>().anchoredPosition = anchorPos;
                child.GetComponent<RectTransform>().sizeDelta = sizeDel;
                child.GetComponent<RectTransform>().localScale = scale;
            }
            else
            {
                child.transform.localPosition = anchorPos;
                child.transform.localScale = scale;
            }
        }
    }
}
